﻿using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace SheepStorage.Service.DataImp
{
    /// <summary>
    /// 后裔转种服务层
    /// </summary>
    public class ProgenyTransferService : IProgenyTransferService
    {
        /// <summary>
        /// 后裔转种
        /// </summary>
        private readonly IBaseRepository<ProgenyTransfer> TransferbaseRepository;

        /// <summary>
        /// 羊只档案
        /// </summary>
        private readonly IBaseRepository<SheepRecord> SheepRecordbaseRepository;

        //构造函数

        public ProgenyTransferService(IBaseRepository<ProgenyTransfer> TransferbaseRepository, IBaseRepository<SheepRecord> SheepRecordbaseRepository)
        {

            this.TransferbaseRepository = TransferbaseRepository;
            this.SheepRecordbaseRepository = SheepRecordbaseRepository;
        }


        /// <summary>
        /// 后裔转种列表显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PageOutput<ProgenyTransfer>> GetProgenyTransfers(string startDate, string endDate, string overbit, int pageIndex, int pageSize)
        {

            var list = TransferbaseRepository.GetAll().Where(c => c.IsDel == 0).ToList();
            if (!string.IsNullOrEmpty(startDate))
            {
                list = list.Where(c => c.TransferDate >= DateTime.Parse(startDate)).ToList();
            }
            if (!string.IsNullOrEmpty(endDate))
            {
                list = list.Where(c => c.TransferDate <= DateTime.Parse(endDate)).ToList();
            }
            if (!string.IsNullOrEmpty(overbit))
            {
                list = list.Where(c => c.OverBit.Contains(overbit)).ToList();
            }








            var result = new PageOutput<ProgenyTransfer>()
            {
                Total = list.Count(),
                PageSize = pageSize
            };
            var entity = list.OrderByDescending(c => c.ProgenyTransferId).Skip
                (pageSize * (pageIndex - 1)).Take(pageSize).ToList();

            result.Data = entity;

            return result;
        }



        /// <summary>
        /// 后裔转种添加-羊只档案修改，转舍记录表，
        /// </summary>
        /// <param name="progenyTransfer"></param>
        /// <returns></returns>
        public async Task<int> AddProgenyTransfer(List<ProgenyTransfer> modelList)
        {
            Random random = new Random();
            using (TransactionScope scope = new TransactionScope())
            {

                foreach (var model in modelList)
                {


                    //单据号生成
                    model.DocumentNumber = "No." + Yitter.IdGenerator.YitIdHelper.NextId().ToString() + model.ProgenyTransferId.ToString() + random.Next(1000, 9999).ToString();
                    //流水号生成
                    model.SerialNumber = DateTime.Now.ToString("yyyyMMddHHmmss") + model.ProgenyTransferId.ToString() + random.Next(1000, 9999).ToString();
                    //添加时间
                    model.AddTime = DateTime.Now;

                    var result = TransferbaseRepository.Add(model);
                    if (result > 0)
                    {
                        //修改羊只档案 
                        var sheeprecord = SheepRecordbaseRepository.GetAll().FirstOrDefault(c => c.OverBit.Contains(model.OverBit));

                        if (sheeprecord != null)
                        {
                            if (model.TransferSex == true)
                            {
                                sheeprecord.SheepRecordType = 1;
                                sheeprecord.UpdateTime = DateTime.Now;

                            }
                            else if (model.TransferSex == false)
                            {
                                sheeprecord.SheepRecordType = 2;
                                sheeprecord.UpdateTime = DateTime.Now;
                            }
                            sheeprecord.UpdateTime = DateTime.Now;
                            SheepRecordbaseRepository.Update(sheeprecord);
                        }


                    }
                    scope.Complete();

                }
                return 1;//添加成功
            }
            throw new Exception("操作失败");
        }

        /// <summary>
        /// 后裔转种逻辑删除/批量删除
        /// </summary>
        /// <param name="TransferId"></param>
        /// <returns></returns>

        public async Task<int> DeleteProgenyTransfer(List<int> TransferId)
        {
            if (TransferId.Count() == 0)
            {
                return -1;//删除失败
            }
            using (var tran = new TransactionScope())
            {
                try
                {
                    //删除后裔转种表记录
                    var entitylist = TransferbaseRepository.GetAll().Where(c => TransferId.Contains(c.ProgenyTransferId)).ToList();

                    foreach (var entity in entitylist)
                    {
                        entity.IsDel = 1;
                        entity.DelTime = DateTime.Now;

                    }
                    TransferbaseRepository.UpdateRange(entitylist);

                    //循环出耳号
                    var overbits = entitylist.Select(c => c.OverBit).ToList();
                    if (overbits.Count > 0)
                    {
                        ///修改羊只档案-回退到上一个状态
                        var sheeprecords = SheepRecordbaseRepository.GetAll().Where(c => overbits.Contains(c.OverBit)).ToList();
                        foreach (var record in sheeprecords)
                        {

                            record.SheepRecordType = 3;//转成后裔
                            record.UpdateTime = DateTime.Now;

                        }
                        SheepRecordbaseRepository.UpdateRange(sheeprecords);
                    }


                    tran.Complete();
                    return 1;//删除成功



                }
                catch (Exception)

                {

                    throw;
                }

            }
        }

        /// <summary>
        /// 根据id反填信息
        /// </summary>
        /// <param name="TransferId"></param>
        /// <returns></returns>
        public async Task<ProgenyTransfer> GetProgenyTransferById(int TransferId)
        {
            var entityinfo = TransferbaseRepository.GetValue(TransferId);
            return entityinfo;

        }

        /// <summary>
        /// 根据id修改信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> UpdateProgenyTransfer(ProgenyTransfer model)
        {

            model.UpdateTime = DateTime.Now;

            var entityinfo = TransferbaseRepository.Update(model);
            return entityinfo;
        }



    }
}
